package com.lingyuan.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.lingyuan.cart.constant.CartConstant;
import com.lingyuan.cart.domain.CartEntity;
import com.lingyuan.cart.domain.CheckCart;
import com.lingyuan.cart.remote.ProductRemoteService;
import com.lingyuan.cart.service.CartService;
import com.lingyuan.common.core.domain.R;
import com.lingyuan.common.core.domain.vo.pms.ProductSkuVo;
import com.lingyuan.common.core.exception.ServiceException;
import com.lingyuan.common.security.utils.SecurityUtils;
import com.lingyuan.system.api.domain.SysUser;
import com.lingyuan.system.api.model.LoginUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName：CartServiceImpl
 * @Author: LeiHao
 * @Date: 2024/9/18 10:16
 * @Description: 购物车业务实现
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ProductRemoteService productRemoteService;

    /* *
     * @Title: addCart
     * @Author: DELL
     * @Date: 2024-09-20 09:42:21
     * @Params: [productId, payNum]
     * @Return: void
     * @Description: 添加购物车
     */
    @Override
    public void addCart(Long skuId, Integer payNum) {
        // 获取用户信息
//        Long userId = getUserId();

        Long userId = 1L;
        if (stringRedisTemplate.boundHashOps(CartConstant.CART_REDIS_KEY + userId).hasKey(String.valueOf(skuId))){
            Object o = stringRedisTemplate.boundHashOps(CartConstant.CART_REDIS_KEY + userId).get(String.valueOf(skuId));
            CartEntity cartEntity = JSON.parseObject(o.toString(), CartEntity.class);
            cartEntity.setPayNum(cartEntity.getPayNum() + payNum);
            cartEntity.setTotalPrice(cartEntity.getProductPrice().multiply(new BigDecimal(cartEntity.getPayNum())));
            stringRedisTemplate.boundHashOps(CartConstant.CART_REDIS_KEY + userId).put(String.valueOf(skuId), JSON.toJSONString(cartEntity));
            return;
        }
        //TODO 获取商品信息
        CartEntity cartEntity = new CartEntity();
        cartEntity.setProductId(skuId);
        cartEntity.setPayNum(payNum);
        R<ProductSkuVo> findByIdR = productRemoteService.findById(skuId);
        if (!R.isSuccess(findByIdR)) {
            throw new ServiceException("获取商品信息失败");
        }
        ProductSkuVo productSkuVo = findByIdR.getData();
        cartEntity.setProductName(productSkuVo.getSkuName());
        cartEntity.setProductImg(productSkuVo.getSkuDefaultImg());
        cartEntity.setProductPrice(productSkuVo.getPrice());
        cartEntity.setTotalPrice(productSkuVo.getPrice().multiply(new BigDecimal(payNum)));
        List<ProductSkuVo.Attr> attrs = productSkuVo.getAttrs();
        List<CartEntity.Attr> attrList = attrs.stream().map(attr -> {
            CartEntity.Attr cartAttr = new CartEntity.Attr();
            BeanUtils.copyProperties(attr, cartAttr);
            return cartAttr;
        }).collect(Collectors.toList());
        cartEntity.setAttrs(attrList);
        //将购物车数据保存到redis
        stringRedisTemplate.boundHashOps(CartConstant.CART_REDIS_KEY + userId).put(String.valueOf(skuId), JSON.toJSONString(cartEntity));
    }
    /* *
     * @Title: updateCart
     * @Author: DELL
     * @Date: 2024-09-20 09:42:30
     * @Params: [skuId, payNum]
     * @Return: void
     * @Description: 修改购物车数量
     */
    @Override
    public void updateCart(Long skuId, Integer payNum) {
        // 获取用户信息
//        Long userId = getUserId();
        Long userId = 1L;

        if (!stringRedisTemplate.boundHashOps(CartConstant.CART_REDIS_KEY + userId).hasKey(String.valueOf(skuId))){
            throw new ServiceException("没有编号为:"+skuId+"的商品!");
        }
        Object o = stringRedisTemplate.boundHashOps(CartConstant.CART_REDIS_KEY + userId).get(String.valueOf(skuId));
        CartEntity cartEntity = JSON.parseObject(o.toString(), CartEntity.class);
        cartEntity.setPayNum(payNum);
        cartEntity.setTotalPrice(cartEntity.getProductPrice().multiply(new BigDecimal(cartEntity.getPayNum())));
        stringRedisTemplate.boundHashOps(CartConstant.CART_REDIS_KEY + userId).put(String.valueOf(skuId), JSON.toJSONString(cartEntity));
    }

    /* *
     * @Title: getCartEntityList
     * @Author: DELL
     * @Date: 2024-09-20 09:42:45
     * @Params: []
     * @Return: List<CartEntity>
     * @Description: 查询当前登录用户购物车
     */
    @Override
    public List<CartEntity> getCartEntityList() {
        //获取当前登录信息
        Long userId = 1L;
        if (!stringRedisTemplate.hasKey(CartConstant.CART_REDIS_KEY + userId)){
            throw new ServiceException("您还没有添加购物车,快去商场看看吧!");
        }
        List<CartEntity> cartEntityList = stringRedisTemplate.boundHashOps(CartConstant.CART_REDIS_KEY + userId)
                .values()
                .stream()
                .map(obj -> JSON.parseObject(obj.toString(), CartEntity.class))
                .collect(Collectors.toList());
        return cartEntityList;
    }


    /* *
     * @Title: findBySkuIdsCartEntityList
     * @Author: DELL
     * @Date: 2024-09-20 09:42:45
     * @Params: [skuIds]
     * @Return: List<CartEntity>
     * @Description: 查询选中的购物车记录
     */
    @Override
    public List<CartEntity> findBySkuIdsCartEntityList(String skuIds) {
        Long userId = 1L;
        String[] skuIdArr = skuIds.split(",");
        List<String> skuIdList = Arrays.stream(skuIdArr).collect(Collectors.toList());
        List<CartEntity> cartEntityList = stringRedisTemplate.boundHashOps(CartConstant.CART_REDIS_KEY + userId)
                .values()
                .stream()
                .map(obj -> {
                    CartEntity cartEntity = JSON.parseObject(obj.toString(), CartEntity.class);
                    return cartEntity;
                })
                .filter(cartEntity -> skuIdList.contains(cartEntity.getProductId().toString()))
                .collect(Collectors.toList());
        return cartEntityList;
    }

    /* *
     * @Title: deleteCart
     * @Author: DELL
     * @Date: 2024-09-20 09:42:53
     * @Params: [skuId]
     * @Return: void
     * @Description: 删除购物车
     */
    @Override
    public void deleteCart(Long skuId) {
        Long userId = 1L;
        if (!stringRedisTemplate.boundHashOps(CartConstant.CART_REDIS_KEY + userId).hasKey(String.valueOf(skuId))){
            throw new ServiceException("没有编号为:"+skuId+"的商品!");
        }
        stringRedisTemplate.boundHashOps(CartConstant.CART_REDIS_KEY + userId).delete(String.valueOf(skuId));

    }

    /* *
     * @Title: deleteBatchCart
     * @Author: DELL
     * @Date: 2024-09-20 09:42:53
     * @Params: [skuIds]
     * @Return: void
     * @Description: 批量删除购物车
     */
    @Override
    public void deleteBatchCart(List<Long> skuIds) {
        skuIds.stream().forEach(skuId->{
            deleteCart(skuId);
        });
    }


    /* *
     * @Title: checkCart
     * @Author: DELL
     * @Date: 2024-09-22 09:56:13
     * @Params: [skuIds]
     * @Return: CheckCart
     * @Description: 计算购物车总价格
     */
    @Override
    public CheckCart checkCart(String skuIds) {
        String[] skuIdArr = skuIds.split(",");
//        判空
        if (skuIdArr.length == 0){
            throw new ServiceException("请选择要结算的商品");
        }
        List<String> skuIdList = Arrays.stream(skuIdArr).collect(Collectors.toList());
        Long userId = 1L;
        List<CartEntity> cartEntityList = stringRedisTemplate.boundHashOps(CartConstant.CART_REDIS_KEY + userId)
                .values()
                .stream()
                .map(obj -> {
                    CartEntity cartEntity = JSON.parseObject(obj.toString(), CartEntity.class);
                    return cartEntity;
                })
                .filter(cartEntity -> skuIdList.contains(cartEntity.getProductId().toString()))
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(cartEntityList)){
            throw new ServiceException("请选择正确的商品的商品");
        }
        CheckCart checkCart = new CheckCart();
        checkCart.setTotalPrice(cartEntityList.stream().map(CartEntity::getTotalPrice).reduce(BigDecimal.ZERO, BigDecimal::add));
        checkCart.setTotalNum(cartEntityList.stream().map(CartEntity::getPayNum).reduce(0, Integer::sum));
        return checkCart;
    }

    /* *
     * @Title: getUserId
     * @Author: DELL
     * @Date: 2024-09-18 10:25:39
     * @Params: []
     * @Return: Long
     * @Description: 获取登录用户编号
     */
    private Long getUserId() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        return sysUser.getUserId();
    }
}
